//
//  WmcUIImageViewEx.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/1.
//

import Kingfisher
import UIKit
import YPBedrock

extension UIImageView {
    /// 加载Wmc图片对象
    /// - Parameter wmcImage: 图片对象
    func wmc_loadImage(wmcImage: WmcImage,
                       completeBlock: YPBlock.OneParam<UIImage?>? = nil)
    {
        wmcImage.loadUIImage { [weak self] image in
            guard let weakSelf = self else { return }
            weakSelf.image = image
            completeBlock?(image)
        }
    }

    func wmc_setImage(_ urlStr: String,
                      params: String? = nil,
                      placeholder: UIImage = "image_placeholder".wmc_image,
                      successBlock: YPBlock.OneParam<RetrieveImageResult>? = nil,
                      failureBlock: YPBlock.OneParam<KingfisherError>? = nil)
    {
        var url = urlStr

        if let params = params {
            var symbol = "?"
            if url.contains(symbol) {
                symbol = "&"
            }
            url.append(contentsOf: "\(symbol)\(params)")
        }

        if let imgUrl = URL(string: url) {
            let urlParts = urlStr.components(separatedBy: "?")
            var key = urlStr
            if urlParts.count == 2 {
                key = urlParts[0]
            }
            let resource = Kingfisher.ImageResource(downloadURL: imgUrl, cacheKey: key)
            kf.setImage(with: .network(resource),
                        placeholder: placeholder,
                        completionHandler: { r in
                            switch r {
                            case let .success(result):
                                successBlock?(result)
                            case let .failure(err):
                                failureBlock?(err)
                            }
                        })
        }
    }
}
